import time
import openai

from openai import OpenAI

from ai_quickstart.openai_translator.ai_translator.model import Model
from ai_quickstart.openai_translator.ai_translator.utils import LOG


class OpenAIModel(Model):
    def __init__(self, model: str, api_key: str, base_url: str):
        self.model = model
        # 初始化OpenAI
        self.client = OpenAI(api_key=api_key, base_url=base_url)

    def make_request(self, prompt):
        attempts = 0
        while attempts < 3:
            try:
                if self.model == 'gpt-4o-mini':
                    response = self.client.chat.completions.create(
                        model=self.model,
                        messages=[{"role": "user", "content": prompt}]
                    )
                    translation = response.choices[0].message.content.strip()
                else:
                    response = self.client.completions.create(
                        model=self.model,
                        prompt=prompt,
                        max_tokens=150,
                        temperature=0
                    )
                    translation = response.choices[0].text.strip()
                return translation, True
            except openai.RateLimitError as e:
                attempts += 1
                if attempts < 3:
                    LOG.warning("已达到速率限制。等待60秒后重试。")
                    time.sleep(60)
                else:
                    raise Exception("已达到速率限制，无法继续翻译。")
            except openai.APIConnectionError as e:
                print("无法访问服务器")
                print(e.__cause__)  # 打印错误原因
            except openai.APIStatusError as e:
                print("API状态错误")
                print(e.status_code + "：" + e.message)  # 打印错误状态码和消息
            except Exception as e:
                raise Exception(f"翻译失败，发生未知错误：{e}")
        return "", False
